/***************************************************************
**常用方法集合
*****************************************************************/
define(["t5/core/dom", "t5/core/events","jquery","msg"], function(dom, events,$) {
	   /*****************************************************************
	   *一些函数的扩展
	   *****************************************************************/ 
		$.fn.serializeObject = function() {
			var o = {};
			var a = this.serializeArray();
			$.each(a, function() {
				if (this.name == 't:formdata') {
					return;
				}
				if (o[this.name]) {
					if (!o[this.name].push) {
						o[this.name] = [ o[this.name] ];
					}
					o[this.name].push(this.value || '');
				} else {
					o[this.name] = this.value || '';
				}
			});
			return o;
		};
		window.gt=function(a,b){
		    return a>b;
		};
		window.ge=function(a,b){
		    return a>=b;
		};
		window.lt=function(a,b){
		    return a<b;
		};
		window.le=function(a,b){
		    return a<=b;
		};
		window.and=function(){
		     var ret=true;
			 $.each(arguments,function(i,n){
			         ret=ret&&n;
			    });
			return ret;
		};
		String.prototype.endWith=function(str){
				if(str==null||str==""||this.length==0||str.length>this.length)
				  return false;
				if(this.substring(this.length-str.length)==str)
				  return true;
				else
				  return false;
				return true;
		};
		Date.prototype.add=function(days){       
			    var ret_milliseconds=this.getTime()+1000*60*60*24*days;        
			    var retDate = new Date();        
			        retDate.setTime(ret_milliseconds);   
			    var strYear = retDate.getFullYear();     
			    var strDay = retDate.getDate();     
			    var strMonth = retDate.getMonth()+1;   
			    if(strMonth<10)     
			    {     
			        strMonth="0"+strMonth;     
			    }    
			    if(strDay<10)     
			    {     
			        strDay="0"+strDay;     
			    }  
			    datastr = strYear+"-"+strMonth+"-"+strDay;   
			    return datastr;   
		};
		String.prototype.startWith=function(str){
				if(str==null||str==""||this.length==0||str.length>this.length)
				  return false;
				if(this.substr(0,str.length)==str)
				  return true;
				else
				  return false;
				return true;
		};
	 _decodeHtml=function(s) {
				s = (s != undefined) ? s : "";
				return (typeof s != "string") ? s : s.replace(/&\w+;|&#(\d+);/g, function(
						$0, $1) {
					var c = {
							"&lt;" : "<",
							"&gt;" : ">",
							"&amp;" : "&",
							"&nbsp;" : " ",
							"&quot;" : "\"",
							"&copy;" : ""
						}[$0];
					if (c == undefined) {
						// Maybe is Entity Number
						if (!isNaN($1)) {
							c = String.fromCharCode(($1 == 160) ? 32 : $1);
						} else {
							c = $0;
						}
					}
					return c;
				});
			
	 };
	_packParam=function(url,param){
			    if(!param){
			       return url;
			    }
			    var urlStr=url;
			    $.each(param, function(i,n) {
			       if(urlStr.indexOf('?')>0){
			            urlStr=urlStr+'&'+i+'='+n;
			        }else{
			            urlStr=urlStr+'?'+i+'='+n;
			        }
				});
				return urlStr;
	};
	_alert=function(info){//弹出提示信息
		$.messager.alert(window.msg.message,info);
	};
	_show=function(info){//弹出提示信息
			   $.messager.show({
					title:window.msg.message,
					msg:info,
					timeout:3000,
					showType:'slide'
				});
			};
	_confirm=function(info,handle){//弹出确认信息
		 		$.messager.confirm(window.msg.confirm,info,function(r){
				    if (r){
				        handle();
				    }
				});
			};
	_prompt=function(info,handle){
			   $.messager.prompt(window.msg.prompt, info, function(r){
					if (r){
						handle(r);
					}
				});
			};
	 _opt2=function(data,hand) {
				if(typeof(data.result)=='undifine'){
					data =eval('(' + data + ')');
				}
				var needDoHand=data && data.result && hand && typeof(hand) == 'function';//是否有handle
				if (data && data.result) {
					if (data.msg != '') {
						if(!needDoHand)
						_alert(data.msg);
					} else {
						if(!needDoHand)
						   _alert(window.msg.optsuccess);
					}
				} else {
					if (data.msg != '') {
						_alert(data.msg);
					} else {
						_alert(window.msg.opterror);
					}
				}
				if(needDoHand){//如果有自己要执行的动作
				   hand(data);
				}
			};
	 _opt=function(data){
		 _opt2(data);
	 };
	 _optshow2=function(data,hand) {
				if(typeof(data.result)=='undifine'){
					data =eval('(' + data + ')');
				}
				var needDoHand=data && data.result && hand && typeof(hand) == 'function';//是否有handle
				if (data && data.result) {
					if (data.msg != '') {
						if(!needDoHand)
						_show(data.msg);
					} else {
						if(!needDoHand)
							_show(window.msg.optsuccess);
					}
				} else {
					if (data.msg != '') {
						_show(data.msg);
					} else {
						_show(window.msg.opterror);
					}
				}
				if(needDoHand){//如果有自己要执行的动作
				   hand(data);
				}
			};
	  _optshow=function(data){
		  _optshow2(data);
	  };
		_getcombogrid=function(id,valueColName){//通过ID和字段名，得到combogrid的值
			   var g = $('#'+id).combogrid('grid');	// get datagrid object
			   var r = g.datagrid('getSelections');	// get the selected row
			   var colName='id';
			   if(valueColName){
			     colName= valueColName;
			   }
			   var retValue='';
			   $.each( r, function(i, n){
				  retValue+=n[colName]+',';
				});
			   return retValue.substring(0,retValue.length-1);
			};
		_extend=function extend(a, b) {//把json对象加到a对象中
				var n;
				if (!a) {
					a = {};
				}
				for (n in b) {
					a[n] = b[n];
				}
				return a;
		    };
		_createElement=function (tag, attribs, styles, parent, nopad) {//创建html元素
				var el = document.createElement(tag);
				if (attribs) {
					this.extend(el, attribs);
				}
				if (nopad) {
					this.extend(el.style, {padding: 0, border: NONE, margin: 0});
				}
				if (styles) {
					this.extend(el.style, styles);
				}
				if (parent) {
					parent.appendChild(el);
				}
				return el;
			};
	_merge=function() {//合并属性
				var i,args = arguments,len,ret = {},
				doCopy = function (copy, original) {
						var value, key;
			
						// An object is replacing a primitive
						if (typeof copy !== 'object') {
							copy = {};
						}
			
						for (key in original) {
							if (original.hasOwnProperty(key)) {
								value = original[key];
			
								// Copy the contents of objects, but not arrays or DOM nodes
								if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
										&& key !== 'renderTo' && typeof value.nodeType !== 'number') {
									copy[key] = doCopy(copy[key] || {}, value);
							
								// Primitives and arrays are copied over directly
								} else {
									copy[key] = original[key];
								}
							}
						}
						return copy;
					};
			
				// If first argument is true, copy into the existing object. Used in setOptions.
				if (args[0] === true) {
					ret = args[1];
					args = Array.prototype.slice.call(args, 2);
				}
			
				// For each argument, extend the return
				len = args.length;
				for (i = 0; i < len; i++) {
					ret = doCopy(ret, args[i]);
				}
			
				return ret;
			};
			garbageBin:'',
	_discardElement=function(element) {//废弃元素
				// create a garbage bin element, not part of the DOM
				if(this.garbageBin==''){
				  this.garbageBin = this.createElement('div');
				}
				// move the node and empty bin
				if (element) {
					this.garbageBin.appendChild(element);
				}
				this.garbageBin.innerHTML = '';
			};			
	_post=function (url, data, formAttributes) {//提交请求
				var name,form;
				// create the form
				form = this.createElement('form', this.merge({
					method: 'post',
					action: url,
					enctype: 'multipart/form-data'
				}, formAttributes), {
					display: 'none'
				}, document.body);
			
				// add the data
				for (name in data) {
					this.createElement('input', {
						type: 'hidden',
						name: name,
						value: data[name]
					}, null, form);
				}
			
				// submit
				form.submit();
			
				// clean up
				this.discardElement(form);
			};
	_showTitle=function(value,len){
			   if(!len) len=20;
			    if(value.length<len){
 		          return  '<span>'+value+'</span>';
 		        }else{
 		           return  '<span title="'+value+'">'+value.substr(0,len)+'...</span>';
 		        }
			},
	_packurl=function(relaurl){//通过相对路径组装国际化的url
			   if(relaurl.startWith('/')){
			      return contextpath+"/"+lan+relaurl;
			   }else{
			      return contextpath+"/"+lan+'/'+relaurl;
			   }
			};
	_openDailog=function(dataopt,url,param){//打开dialog,isOuter是否是外网地
			       var idStr=dataopt.id;
			       if(!idStr){
			          idStr="_mainFrame";
			       }
			       var urlstr=url;
			      // alert(urlstr);
			       if(!url.startWith('http://') && !url.startWith('https://')){
			           urlstr=this.packParam(this.packurl(url),param);
			       }
			       var ifm = jQuery('<iframe id="'+idStr+'" name="'+idStr+'" width="100%" height="100%" style="border: 0" src="'+urlstr+'"  frameborder="no" border="0"></iframe>');
			   	   var dataoptTrue={width:1160,height:650,modal:true,content:ifm};
			       if(dataopt){
			          if(dataopt.onClose){
			              dataopt.onBeforeClose=dataopt.onClose;
			          }
			          dataoptTrue=_merge(dataoptTrue,dataopt);
			       }
			       dataoptTrue=this.merge(dataoptTrue,{onClose:function(){jQuery(this).dialog('destroy');}});//保证在关闭的时候消毁该对象
			       jQuery('<div/>').dialog(dataoptTrue);
			      // jQuery('#'+idStr).attr("src",);
			};
	_fixcombobox=function(comboboxId){//重新计算combobox的高度，传入combobox的Ｉd
			  // alert('id='+comboboxId);
			    var _childSize=$('#'+comboboxId).combobox('panel').panel('body')[0].childElementCount;  
  	        	var _trueheight=_childSize*24>200?200:_childSize*24;	      
  	        	$('#'+comboboxId).combobox('panel').panel('resize',{height:_trueheight});
			};
	_fix=function(){//改变大小时重新计算屏幕的宽度和高度
			   if(!arguments||arguments.length==0){//没有传入参数直接跳出
			      return;
			   }
			   var mainid=arguments[0];//主体Id，必须要是datagrid
			   var minwidth=1050;
				try{
					jQuery('.frame_title').width(lt(jQuery(window).width(),minwidth)?minwidth:jQuery(window).width()-10);
					var widthTrue=lt(jQuery(window).width(),minwidth)?minwidth:jQuery(window).width();
					var heightTrue =jQuery(window).height()-10;
					$.each(arguments,function(i,n){
					   if(i>0){
					     heightTrue=heightTrue-jQuery('#'+n+'').outerHeight();
					   }
			    	});
					heightTrue=heightTrue-40;
					widthTrue=widthTrue-5;//为使右边的边框显示出来
					try{
					   jQuery('#'+mainid).datagrid('resize',{
			        		width:widthTrue,
			        		height:heightTrue
			           });
					}catch(e){//如果不是datagrid试着运行panel，暂时只支持这两种组件重设大小
					    try{
					      jQuery('#'+mainid).tabs('resize',{
			        		 width:widthTrue,
			        		 height:heightTrue
			           	   });
			           	   jQuery.each(jQuery('#'+mainid).find("iframe"),function(index,elem){//tabs 的方法　resize不起作用。用这段打补丁
					            jQuery(elem).height(heightTrue);
					       });
					    }catch(e){
					        jQuery('#'+mainid).panel('resize',{
			        		width:widthTrue,
			        		height:heightTrue
			           	   });
					    } 					  
					}
				} catch(e){console.info(e);}
		};
	var retobj={decodeHtml:_decodeHtml,packParam:_packParam,alert:_alert,show:_show,confirm:_confirm,prompt:_prompt,opt:_opt,opt2:_opt2,optshow:_optshow,optshow2:_optshow2,getcombogrid:_getcombogrid,extend:_extend,createElement:_createElement,merge:_merge,discardElement:_discardElement,post:_post,showTitle:_showTitle,packurl:_packurl,openDailog:_openDailog,fixcombobox:_fixcombobox,fix:_fix};
	$.rjzjh=retobj;
	return retobj;
 });